class PixelGame extends Phaser.Scene {
    constructor() {
        super({ key: 'PixelGame' });
        this.worldSize = 512;
        this.tileSize = 16;
        this.players = new Map();
        this.blocks = new Map();
        this.inventory = {
            wood: 0,
            stone: 0,
            coal: 0,
            iron: 0,
            gold: 0
        };
        this.selectedBlock = 1;
    }

    preload() {
        this.createPixelArt();
    }

    createPixelArt() {
        // 创建简单的像素艺术纹理
        this.add.graphics()
            .fillStyle(0x8B4513)
            .fillRect(0, 0, 16, 16)
            .generateTexture('wood', 16, 16);

        this.add.graphics()
            .fillStyle(0x808080)
            .fillRect(0, 0, 16, 16)
            .generateTexture('stone', 16, 16);

        this.add.graphics()
            .fillStyle(0x000000)
            .fillRect(0, 0, 16, 16)
            .generateTexture('coal', 16, 16);

        this.add.graphics()
            .fillStyle(0xC0C0C0)
            .fillRect(0, 0, 16, 16)
            .generateTexture('iron', 16, 16);

        this.add.graphics()
            .fillStyle(0xFFD700)
            .fillRect(0, 0, 16, 16)
            .generateTexture('gold', 16, 16);

        this.add.graphics()
            .fillStyle(0x228B22)
            .fillRect(0, 0, 16, 16)
            .generateTexture('grass', 16, 16);

        this.add.graphics()
            .fillStyle(0x654321)
            .fillRect(0, 0, 16, 16)
            .generateTexture('dirt', 16, 16);
    }

    create() {
        this.setupWorld();
        this.setupPlayer();
        this.setupControls();
        this.setupNetwork();
        this.setupUI();
    }

    setupWorld() {
        // 创建世界地图
        this.map = this.make.tilemap({ 
            tileWidth: this.tileSize, 
            tileHeight: this.tileSize, 
            width: this.worldSize / this.tileSize, 
            height: this.worldSize / this.tileSize 
        });

        const tileset = this.map.addTilesetImage('tiles');
        
        // 创建地面层
        this.groundLayer = this.map.createBlankLayer('ground', tileset);
        this.blockLayer = this.map.createBlankLayer('blocks', tileset);

        // 生成地形
        this.generateTerrain();
    }

    generateTerrain() {
        const noise = this.generateNoise();
        
        for (let x = 0; x < this.worldSize / this.tileSize; x++) {
            for (let y = 0; y < this.worldSize / this.tileSize; y++) {
                const height = noise[x][y];
                
                if (y < 10) {
                    this.groundLayer.putTileAt(0, x, y); // 空气
                } else if (y < 15) {
                    this.groundLayer.putTileAt(1, x, y); // 草地
                } else {
                    this.groundLayer.putTileAt(2, x, y); // 泥土
                }
            }
        }
    }

    generateNoise() {
        const noise = [];
        for (let x = 0; x < this.worldSize / this.tileSize; x++) {
            noise[x] = [];
            for (let y = 0; y < this.worldSize / this.tileSize; y++) {
                noise[x][y] = Math.random();
            }
        }
        return noise;
    }

    setupPlayer() {
        this.player = this.physics.add.sprite(
            Math.random() * this.worldSize,
            100,
            'player'
        );
        
        this.player.setCollideWorldBounds(true);
        this.cameras.main.startFollow(this.player);
        this.cameras.main.setBounds(0, 0, this.worldSize, this.worldSize);
    }

    setupControls() {
        this.cursors = this.input.keyboard.createCursorKeys();
        this.wasd = this.input.keyboard.addKeys('W,S,A,D');
        
        // 空格键挖掘
        this.input.keyboard.on('keydown-SPACE', () => {
            this.mineBlock();
        });
        
        // E键放置
        this.input.keyboard.on('keydown-E', () => {
            this.placeBlock();
        });
        
        // 数字键选择方块
        for (let i = 1; i <= 5; i++) {
            this.input.keyboard.on(`keydown-${i}`, () => {
                this.selectedBlock = i;
                this.updateUI();
            });
        }
    }

    mineBlock() {
        const worldPoint = this.input.activePointer.positionToCamera(this.cameras.main);
        const tileX = Math.floor(worldPoint.x / this.tileSize);
        const tileY = Math.floor(worldPoint.y / this.tileSize);
        
        const tile = this.blockLayer.getTileAt(tileX, tileY);
        if (tile) {
            const blockType = this.getBlockType(tile.index);
            if (blockType) {
                this.inventory[blockType]++;
                this.blockLayer.removeTileAt(tileX, tileY);
                this.updateUI();
                
                // 同步到服务器
                if (window.network) {
                    window.network.mineBlock(tileX, tileY);
                }
            }
        }
    }

    placeBlock() {
        const worldPoint = this.input.activePointer.positionToCamera(this.cameras.main);
        const tileX = Math.floor(worldPoint.x / this.tileSize);
        const tileY = Math.floor(worldPoint.y / this.tileSize);
        
        const blockType = this.getBlockTypeById(this.selectedBlock);
        if (blockType && this.inventory[blockType] > 0) {
            this.inventory[blockType]--;
            this.blockLayer.putTileAt(this.selectedBlock, tileX, tileY);
            this.updateUI();
            
            // 同步到服务器
            if (window.network) {
                window.network.placeBlock(tileX, tileY, this.selectedBlock);
            }
        }
    }

    getBlockType(tileIndex) {
        const types = ['wood', 'stone', 'coal', 'iron', 'gold'];
        return types[tileIndex - 1] || null;
    }

    getBlockTypeById(id) {
        const types = ['wood', 'stone', 'coal', 'iron', 'gold'];
        return types[id - 1] || null;
    }

    setupNetwork() {
        if (window.network) {
            window.network.onBlockUpdate = (x, y, type, action) => {
                if (action === 'mine') {
                    this.blockLayer.removeTileAt(x, y);
                } else if (action === 'place') {
                    this.blockLayer.putTileAt(type, x, y);
                }
            };
            
            window.network.onPlayerJoin = (playerData) => {
                this.addOtherPlayer(playerData);
            };
            
            window.network.onPlayerLeave = (playerId) => {
                this.removeOtherPlayer(playerId);
            };
            
            window.network.onPlayerMove = (playerId, x, y) => {
                this.updateOtherPlayer(playerId, x, y);
            };
        }
    }

    addOtherPlayer(playerData) {
        const player = this.physics.add.sprite(playerData.x, playerData.y, 'player');
        player.setTint(0xff0000);
        this.players.set(playerData.id, player);
    }

    removeOtherPlayer(playerId) {
        const player = this.players.get(playerId);
        if (player) {
            player.destroy();
            this.players.delete(playerId);
        }
    }

    updateOtherPlayer(playerId, x, y) {
        const player = this.players.get(playerId);
        if (player) {
            player.x = x;
            player.y = y;
        }
    }

    setupUI() {
        this.updateUI();
    }

    updateUI() {
        if (window.updateInventory) {
            window.updateInventory(this.inventory);
        }
    }

    update() {
        // 玩家移动
        const speed = 200;
        
        if (this.wasd.A.isDown) {
            this.player.setVelocityX(-speed);
        } else if (this.wasd.D.isDown) {
            this.player.setVelocityX(speed);
        } else {
            this.player.setVelocityX(0);
        }
        
        if (this.wasd.W.isDown) {
            this.player.setVelocityY(-speed);
        } else if (this.wasd.S.isDown) {
            this.player.setVelocityY(speed);
        } else {
            this.player.setVelocityY(0);
        }
        
        // 同步位置到服务器
        if (window.network && Math.random() < 0.1) {
            window.network.updatePosition(this.player.x, this.player.y);
        }
    }
}

// 游戏配置
const config = {
    type: Phaser.AUTO,
    width: window.innerWidth,
    height: window.innerHeight,
    parent: 'game-canvas',
    backgroundColor: '#87CEEB',
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 0 },
            debug: false
        }
    },
    scene: PixelGame
};

// 初始化游戏
let game;
function initGame() {
    game = new Phaser.Game(config);
}